<template>
  <div>
    <!-- 操作按钮 -->
    <div class="actions-bar">
      <el-button type="primary" @click="showAddDialog">
        <el-icon class="mr-2"><plus /></el-icon>
        添加外部人员
      </el-button>
      <el-button type="primary" @click="showImportDialog">
        <el-icon class="mr-2"><upload /></el-icon>
        批量导入
      </el-button>
    </div>

    <!-- 外部人员表格 -->
    <qs-table
      :finally-columns="finallyColumns"
      :layout="layout"
      :list="list"
      :list-loading="listLoading"
      :query-form="queryForm"
      :total="total"
      @handle-current-change="handleCurrentChange"
      @handle-delete="handleDelete"
      @handle-edit="handleEdit"
      @handle-size-change="handleSizeChange"
      @update:query-form="updateQueryForm"
    />

    <!-- 用户表单组件 -->
    <user-form-component ref="userFormRef" :is-external-user="true" @success="handleFormSuccess" @close="handleFormClose" />

    <!-- 导入组件 -->
    <user-import-component ref="importRef" :is-external-user="true" @success="handleImportSuccess" @close="handleImportClose" />
  </div>
</template>

<script lang="ts" setup>
import { Plus, Upload } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, onMounted, ref } from 'vue'
import { tableColumns } from '../config'
import UserFormComponent from './UserFormComponent.vue'
import UserImportComponent from './UserImportComponent.vue'
import Public from '/@/api/public'

// 定义外部人员类型
interface ExternalUser {
  id?: number
  deptId: number | null
  name: string
  mobile: string
  email: string
  [key: string]: any
}

const emit = defineEmits(['refresh'])

// 组件引用
const userFormRef = ref()
const importRef = ref()

// 表格数据
const list = ref<ExternalUser[]>([])
const listLoading = ref(false)
const total = ref(0)
const layout = ref('total, sizes, prev, pager, next, jumper')

// 查询表单
const queryForm = ref({
  page: 1,
  limit: 20,
  deptId: null,
})

// 最终显示的列
const checkList = ref(tableColumns.value.map((col: any) => col.label))
const finallyColumns = computed(() => tableColumns.value.filter((item: any) => checkList.value.includes(item.label)))

// 显示添加外部人员弹窗
const showAddDialog = () => {
  userFormRef.value?.openAdd()
}

// 显示编辑外部人员弹窗
const handleEdit = (row: ExternalUser) => {
  userFormRef.value?.openEdit(row)
}

// 显示导入弹窗
const showImportDialog = () => {
  importRef.value?.open()
}

// 处理导入成功
const handleImportSuccess = () => {
  fetchData()
  emit('refresh')
}

// 处理导入关闭
const handleImportClose = () => {
  // 可以在这里进行一些清理工作
}

// 处理表单提交成功
const handleFormSuccess = () => {
  fetchData()
  emit('refresh')
}

// 处理表单关闭
const handleFormClose = () => {
  // 可以在这里进行一些清理工作
}

// 获取外部人员数据
const fetchData = async () => {
  listLoading.value = true
  try {
    const response = await Public.getDetailApi({
      url: '/api/user',
      params: {
        ...queryForm.value,
        isExternal: true,
      },
    })

    if (response.code === 0 && response.result) {
      list.value = response.result.rows || []
      total.value = response.result.count || 0
    } else {
      list.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取外部人员列表失败:', error)
    list.value = []
    total.value = 0
  } finally {
    listLoading.value = false
  }
}

// 删除外部人员
const handleDelete = (id: number) => {
  ElMessageBox.confirm('确定要删除该外部人员吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        const response = await Public.delApi({ url: '/api/user', id })

        if (response.code === 0) {
          ElMessage.success('删除成功')
          fetchData()
          emit('refresh')
        } else {
          ElMessage.error(response.message || '删除失败')
        }
      } catch (error) {
        console.error('删除失败:', error)
        ElMessage.error('删除失败，请稍后重试')
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 更新查询表单
const updateQueryForm = (newQueryForm: any) => {
  queryForm.value = { ...newQueryForm }
  fetchData()
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  queryForm.value.limit = val
  queryForm.value.page = 1
  fetchData()
}

// 当前页改变
const handleCurrentChange = (val: number) => {
  queryForm.value.page = val
  fetchData()
}

// 初始化
onMounted(() => {
  fetchData()
})

// 对外暴露的方法
defineExpose({
  showAddDialog,
  showImportDialog,
})
</script>

<style scoped>
.actions-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.mr-2 {
  margin-right: 8px;
}
</style>
